<template>
  <div>
    <el-select v-model="materialStorage" :clearable="clearable" :placeholder="placeholder" class="width-120" filterable
               :disabled="disabled" style="width: 100%;" @change="materialStorageChange">
      <el-option v-for="item in materialStorageList" :key="item.storageId" :label="item.storageName" :value="item.storageId">
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts" setup>

import {listMaterialStorageDept} from '@/api/material/materialStorageDept'

const materialStorage = ref('')
const emits = defineEmits(["materialStorageChange"])
// 库房list
const materialStorageList = ref<any>([])
const props = defineProps({
  placeholder: {
    type: String,
    default: "请选择"
  },
  value: {
    type: String,
    default: ''
  },
  valueStorageId: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  // 机构id
  orgId: {
    type: String,
    default: ''
  }
})

watch(() => props.orgId, (_newValue, _oldValue) => {
  getMaterialStorageList()
}, {deep: true, immediate: true})

watch(() => props.value, (newValue, _oldValue) => {
  materialStorage.value = newValue
}, {deep: true, immediate: true})

watch(() => props.valueStorageId, (newValue, _oldValue) => {
  let index = materialStorageList.value.findIndex((item: any) => {
    return newValue == item.storageCode
  })
  if (index > -1) {
    materialStorage.value = materialStorageList.value[index].storageId
  }
}, {deep: true, immediate: true})

function setValue(value) {
  materialStorage.value = value
}

// 获取本机构库房字典list
function getMaterialStorageList() {
  const param = {delFlag: '0', orgId: props.orgId}
  listMaterialStorageDept(param).then(res => {
    materialStorageList.value = res.data
    let index = materialStorageList.value.findIndex((item: any) => {
      return props.valueStorageId === item.storageCode
    })
    if (index > -1) {
      materialStorage.value = materialStorageList.value[index].storageId
      emits("materialStorageChange", materialStorageList.value[index])
    }
  })
}

function materialStorageChange(value) {
  let materialStorageInfo = {}
  let index = materialStorageList.value.findIndex(item => {
    return item.storageId === value
  })
  if (index > -1) {
    materialStorageInfo = materialStorageList.value[index]
  }
  emits("materialStorageChange", materialStorageInfo)
}

defineExpose({
  setValue
})
</script>

<script lang="ts">

export default {
  name: "materialStorageDept"
}
</script>

<style scoped></style>
